import axios from 'axios'
import { getToken } from '@/utils/auth'

const service = axios.create({
    baseURL: import.meta.env.VITE_BASE_API as string,
    timeout: 9999
})
// http request 拦截器
service.interceptors.request.use(
  (config: any) => {
		// 全局添加 token
		if (getToken()) {
			config.headers['Authorization'] = getToken()
		}
		return config
	},
	(error) => {
		console.error(error)
		return Promise.reject(error)
	}
)

// http response 拦截器
service.interceptors.response.use(
	(response) => {
		if (response.data.code === 200) {
			window.$message.success(response.data.msg)
			return response.data.data
		} else if (response.data.code === 500) {
			window.$message.error(response.data.msg)
			return response.data
		} else if (response.data.code === 401) {
			location.href = '/login'
		}
		return response.data
	},
	(error) => {
		let { message } = error
		if (error.response && error.response.status && error.response.status === 403) {

		}
		// 网络超时
		if (error.message && error.message.includes('timeout')) {
			message = '请求超时'
		}
		if (error.response && error.response.status && error.response.status === 500) {
			// 没有权限
			message = '接口异常'
		}
		if (error.response && error.response.status && error.response.status === 401) {
			// 没有权限
			message = '登录信息已失效，请重新登录'
			location.href = '/login'
		}
		window.$message.error(message)
		return Promise.reject(error)
	}
)

export default service